package com.kbook.action.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.kbook.action.Action;
import com.kbook.bean.UserBean;
import com.kbook.dao.ChartsDao;
import com.kbook.dao.NovelDao;
import com.kbook.dao.impl.ChartsDaoImpl;
import com.kbook.dao.impl.NovelDaoImpl;
import com.kbook.log.LogWriter;
import com.kbook.tool.Constants;
import com.kbook.vo.Charts;
import com.kbook.vo.ChartsMap;

public class HomeAction extends AbstractAction {

	private static final Logger logger = Logger.getLogger("HomeAction");
	
	@Override
	protected Object doAction(UserBean user, Map params) throws Exception {
		// TODO Auto-generated method stub
		Map homeMap = new HashMap();
		//获取小说分类
		Action categoryAction =  new CategoryAction();
		homeMap.put("category", categoryAction.excute(user, params));
		
		ChartsDao chartsDao = new ChartsDaoImpl();
		List<Charts> chartsList = chartsDao.queryAll();
		
		
		
		homeMap.put("chartMap", packageChartsMap(chartsList));
		
		NovelDao novelDao = new NovelDaoImpl();
		homeMap.put("totalNum", novelDao.queryTotal());
		/*ChartsMap chartsMap = packageChartsMap(chartsList);
		List<Charts> testList = chartsMap.getEditorRecommend();
		for(Charts chart : testList){
			System.out.println(chart.getName());
		}*/
		
		return homeMap;
	}
	
	
	
	@Override
	protected void afterAction(Object obj, UserBean user, Map params) {
		// TODO Auto-generated method stub
		List<String> logParams = new ArrayList<String>();
		logParams.add((String)params.get("ip"));
		logParams.add((String)params.get("ua"));
		logParams.add((String)params.get("cid"));

		LogWriter.getInstance().createLog(logParams, logger);
	}



	private ChartsMap packageChartsMap(List<Charts> chartsList){
		ChartsMap chartMap = new ChartsMap();
		Map<Short, List<Charts>> map = new HashMap<Short, List<Charts>>();
		for(Charts charts : chartsList){
			//System.out.println(charts.getName());
			short chartId = charts.getChartId();
			List<Charts> innerChartsList = map.get(chartId);
			if(innerChartsList == null){
				innerChartsList = new ArrayList<Charts>();
				map.put(chartId, innerChartsList);
			}
			
			innerChartsList.add(charts);
		}
		
		chartMap.setClassic(map.get(Constants.CHART_CLASSIC));
		chartMap.setDushi(map.get(Constants.CHART_DUSHI));
		chartMap.setEditorRecommend(map.get(Constants.CHART_EDITOR_RECOMMEND));
		chartMap.setHotest(map.get(Constants.CHART_HOTEST));
		chartMap.setLingyi(map.get(Constants.CHART_LINGYI));
		chartMap.setLishi(map.get(Constants.CHART_LISHI));
		chartMap.setNewBook(map.get(Constants.CHART_NEW_BOOK));
		chartMap.setNewest(map.get(Constants.CHART_NEWEST));
		chartMap.setQihuan(map.get(Constants.CHART_QIHUAN));
		chartMap.setWangyou(map.get(Constants.CHART_WANGYOU));
		chartMap.setWuxia(map.get(Constants.CHART_WUXIA));
		
		return chartMap;
	}

}
